import React from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Spin, message, Badge, Col, Row, Drawer, Button, Table } from 'antd';
import ProTable, { EditableProTable } from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { ProductType } from '../../../model';
import { DrawerForm, ModalForm, ProFormText, ProFormUploadDragger } from '@ant-design/pro-form';
import UpDownLabel from '../../../components/Common/UpDownLabel';
import { orderSendListData, orderDeliveryDataById, delivery, orderDetailDataById, exportorderSend } from '../service';
import { FileExcelOutlined } from '@ant-design/icons';
import { InputNumber } from 'antd';
import { Modal } from 'antd';
import { exportFile, manufacturerOption,productPropertyOption } from '@/utils/utils';
import html2canvas from 'html2canvas';

class Delivery extends React.Component {
  actionRef = React.createRef<ActionType>();
  formRef = React.createRef<ActionType>();
  state = {
    activeKey: 'tab1',
    proModalVisible: false,
    detailFlag: false,
    sentFlag: false,
    proData: [],
    record: {},
    editableKeys: {},
    spinningFlag: false,
    initData: {},
    showImport: false,
    errorVisible: false,
    errInfo: [],
    dealerCode: ''
  };
  onFileUpload = (info: any) => {
    if (info.file.status !== 'uploading') {}

    if (info.file.status === 'done') {
      if (info.file.response.errorCode === '200') {
        message.success(`${info.file.name} 上传成功`);
        this.actionRef.current?.reloadAndRest?.();
        this.setState({
          showImport: false
        });
      } else {
        this.setState({
          errorVisible: true,
          errInfo: info.file.response.data
        });

        if (info.file.response.msg) {
          message.error('上传失败: ' + info.file.response.msg);
        } else {
          message.error('上传失败: ' + info.file.response.errorMessage);
        }
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败！`);
    }
  };
  renderBadge = (count: number, active = false) => {
    return <Badge count={count} style={{
      marginTop: -2,
      marginLeft: 4,
      color: active ? '#1890FF' : '#999',
      backgroundColor: active ? '#E6F7FF' : '#eee'
    }}  />;
  };
  columns: ProColumns[] = [{
    title: '订单号',
    width:180,
    dataIndex: 'order_number',
    fieldProps: {
      onPressEnter: () => {
        this.formRef?.current?.submit();
      }
    }
  }, {
    title: '客户代码',
    dataIndex: 'dealerCode',
    fieldProps: {
      onPressEnter: () => {
        this.formRef?.current?.submit();
      }
    }
  }, {
    title: '客户名称',
    dataIndex: 'dealerName',
    ellipsis:true,
    fieldProps: {
      onPressEnter: () => {
        this.formRef?.current?.submit();
      }
    }
  }, {
    title: '收货电话',
    dataIndex: 'mobile',
    hideInSearch: true
  }, {
    title: '订货日期',
    dataIndex: 'order_time',
    hideInSearch: true
  }, {
    title: '交货日期',
    dataIndex: 'delivery_time',
    hideInSearch: true
  }, {
    title: '选择日期',
    valueType: 'dateRange',
    dataIndex: 'date',
    hideInTable: true
  }, {
    title: '审核日期',
    valueType: 'dateRange',
    dataIndex: 'approvalDate',
    hideInTable: true
  }, {
    title: '审核日期',
    dataIndex: 'approval_time',
    hideInSearch: true
  }, {
    title: '操作',
    key: 'option',
    fixed:'right',
    width: 150,
    valueType: 'option',
    render: (_, record) => [<a key='show' onClick={() => this.detail(record)}>详情</a>, <a key='show' onClick={() => this.showSentInfo(record)}>发货</a>]
  }];
  printOrder = () => {
    const el: any = document.getElementById('billDetails');
    var scrollTop = document.documentElement.scrollTop;
    document.documentElement.scrollTop = 0;
    const win: any = window.open('', 'printwindow');
    let that = this;
    html2canvas(el, {
      useCORS: true
    }).then(canvas => {
      win.document.body.appendChild(canvas);
      win.print();
      win.close();
      document.documentElement.scrollTop = scrollTop;
      that.setState({
        detailFlag: false
      });
    });
  }; //表头信息以及表值设置

  pcolumns: ProColumns<ProductType>[] = [{
    title: '产品名称',
    dataIndex: 'product_name',
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    }
  }, {
    title: '产品型号',
    dataIndex: 'product_standard'
  },
  {
    title:'产品性质',
    dataIndex: 'productProperty',
    width:150,
    valueType:'select',
    valueEnum:productPropertyOption(),
  },
  {
    title: '单位',
    dataIndex: 'packing_unit'
  }, {
    title: '订货数量',
    dataIndex: 'numbs'
  }, {
    title: '合计',
    dataIndex: 'numbs_count',
    width: 70,
    colSpan: 1,
    align: 'center',
    render: (value: any, record: any) => {
      const obj = {
        children: value,
        props: {}
      };
      obj.props.rowSpan = record.name_count;
      return obj;
    }
  }, {
    title: '已发货',
    dataIndex: 'send_numbs'
  }, {
    title: '备注',
    dataIndex: 'remarks',
    width: 100,
    ellipsis: true
  }];
  errorColumn = [{
    title: '错误行',
    dataIndex: 'rownum'
  }, {
    title: '错误信息',
    dataIndex: 'errerMsg'
  }]; //表头信息以及表值设置

  pCreatecolumns = [ {
    title: '产品名称',
    ellipsis: true,
    dataIndex: 'product_name',
    renderText: (_, record: any) => {
      if (record.is_gifts == 1) {
        return `${record.product_name}(赠品)`;
      }

      return record.product_name;
    }
  }, {
    ellipsis: true,
    title: '产品型号',
    dataIndex: 'product_standard'
  },{
    title:'产品性质',
    dataIndex: 'productProperty',
    width:150,
    valueType:'select',
    valueEnum:productPropertyOption(),
  }, {
    width: 130,
    title: '批号',
    dataIndex: ''
  }, {
    title: '待发货',
    width: 80,
    dataIndex: 'numbs',
    render: (_, record: any) => {
      return record.numbs - record.send_numbs;
    }
  }, {
    width: 150,
    title: '失效日期',
    dataIndex: ''
  }, {
    width: 60,
    title: '单位',
    dataIndex: 'packing_unit',
    ellipsis:true,
  }, {
    title: '备注',
    dataIndex: 'remarks',
    width: 100,
    ellipsis: true
  }, {
    width: 150,
    title: '操作',
    valueType: 'option',
    render: (text, record, _, action) => [<a key='add' hidden={record.numbs - record.send_numbs + record.return_numbs == 0} onClick={() => {
      record.sub.push({
        pIndex: record.pIndex,
        batch: '',
        numbs: 0,
        validityDate: undefined,
        productId: record.productId,
        orderProductId: record.orderProductId
      });
      record.pIndex++;
      var editableKeys: any = this.state.editableKeys;
      editableKeys[record.productId] = record.sub.map((item: any) => item.pIndex);
      this.setState({
        editableKeys: { ...editableKeys
        }
      });
      this.setState({
        proData: [...this.state.proData]
      });
    }}>
          添加
        </a>]
  }];
  expandedRowRender = (val:any) => {
    const columns = [{
      title: '',
      dataIndex: 'numbs',
      width: 70,
      render: () => [],
      editable: false
    }, {
      title: '',
      dataIndex: 'numbs',
      render: () => [],
      editable: false
    }, {
      title: '',
      dataIndex: 'numbs',
      render: () => [],
      editable: false
    }, {
      title: '',
      dataIndex: 'numbs',
      width:150,
      render: () => [],
      editable: false
    },, {
      title: '批号',
      dataIndex: 'batch',
      width: 130,
      formItemProps: (form, {
        rowIndex
      }) => {
        return {
          rules: [{
            required: true,
            message: '批号必填'
          }]
        };
      }
    }, {
      title: '发货数量',
      dataIndex: 'numbs',
      width: 80,
      formItemProps: (form, {
        rowIndex
      }) => {
        return {
          rules: [{
            required: true,
            message: '发货数量必填'
          }]
        };
      },
      renderFormItem: (_, {
        type,
        defaultRender,
        formItemProps,
        fieldProps,
        ...rest
      }, form) => {
        return <InputNumber {...fieldProps} placeholder='请输入' precision={0} />;
      }
    }, {
      title: '失效日期',
      dataIndex: 'validityDate',
      width: 150,
      valueType: 'date',
      formItemProps: (form, {
        rowIndex
      }) => {
        return {
          rules: [{
            required: true,
            message: '失效日期必填'
          }]
        };
      }
    }, {
      title: '',
      dataIndex: 'numbs',
      width: 50,
      render: () => [],
      editable: false
    }, {
      title: '',
      dataIndex: 'numbs',
      render: () => [],
      editable: false
    }, {
      title: '操作',
      valueType: 'option',
      width: 150,
      render: () => {
        return null;
      }
    }];
    const data = [...val.sub];
    return <EditableProTable columns={columns} value={data} rowKey='pIndex' toolBarRender={false} showHeader={false} pagination={false} size='small' search={false} toolbar={[]} locale={{
      emptyText: '暂无'
    }} recordCreatorProps={false} onChange={data => {
      var editableKeys: any = this.state.editableKeys;
      editableKeys[val.productId] = data.map((item: any) => item.pIndex);
      this.setState({
        editableKeys: { ...editableKeys
        }
      });
      this.setState({
        proData: [...this.state.proData]
      });
    }} editable={{
      editableKeys: this.state.editableKeys[val.productId],
      type: 'multiple',
      onChange: v => {
        var editableKeys: any = this.state.editableKeys;
        editableKeys[val.productId] = v;
        this.setState({
          editableKeys: { ...editableKeys
          }
        });
      },
      actionRender: (row, config, defaultDoms) => {
        return [defaultDoms.delete];
      },
      onDelete: async (key: any, record: any) => {
        var newData = val.sub.filter((item: any) => item.id !== record.id);
        val.sub = newData;
        this.setState({
          proData: [...this.state.proData]
        });
      },
      onValuesChange: (record, recordList) => {
        // console.log(record)
        val.sub = recordList;
        this.setState({
          proData: [...this.state.proData]
        });
      }
    }}/>;
  };
  detail = async (record: any) => {
    this.setState({
      spinningFlag: true
    });
    var param: any = {
      orderId: record.id
    };
    var val = await orderDetailDataById(param);

    if (val.errorCode === '200') {
      this.setState({
        detailFlag: true,
        initData: val.data,
        dealerCode: record.dealerCode
      });
    } else {
      message.error('获取订单详情失败');
    }

    this.setState({
      spinningFlag: false
    });
  };
  showSentInfo = async (record: any) => {
    this.setState({
      spinningFlag: true
    });
    var val = await orderDeliveryDataById({
      orderId: record.id
    });

    if (val.errorCode === '200') {
      val.data.forEach((element: any) => {
        if (!element.sub) {
          element.sub = [];
        }

        element.pIndex = 0;
      });
      this.setState({
        proData: val.data,
        record: record,
        dealerCode: record.dealerCode
      });
      this.setState({
        sentFlag: true
      });
    } else {
      message.error('获取订单信息失败');
    }

    this.setState({
      spinningFlag: false
    });
  };

  choosePro() {
    this.setState({
      proModalVisible: true
    });
  }

  handleCancel = () => {
    this.setState({
      errorVisible: false,
      errInfo: []
    });
  };

  render() {
    const expandedRowRender = this.expandedRowRender;
    return <PageContainer>
    <ProTable  scroll={{x:1400}} columns={this.columns} actionRef={this.actionRef} formRef={this.formRef} request={(params, sorter, filter) => {
        if (this.state.activeKey === 'tab1') {
          params.complete = 0;
        } else {
          params.complete = 1;
        }

        if (params.date) {
          params.beginDate = params.date[0];
          params.endDate = params.date[1];
          params.date = undefined;
        }

        if (params.approvalDate) {
          params.approvalBeginDate = params.approvalDate[0];
          params.approvalEndDate = params.approvalDate[1];
          params.approvalDate = undefined;
        }

        return orderSendListData({ ...params,
          filter
        });
      }} toolBarRender={() => [<Button  type='primary' key='primary' onClick={async () => {
        this.setState({
          showImport: true
        });
      }}>
      <FileExcelOutlined/>导入发货单
      </Button>]} toolbar={{
        menu: {
          type: 'tab',
          activeKey: this.state.activeKey,
          items: [{
            key: 'tab1',
            label: <span >待发货{this.renderBadge(0, this.state.activeKey === 'tab1')}</span>
          }, {
            key: 'tab2',
            label: <span>已发货{this.renderBadge(0, this.state.activeKey === 'tab2')}</span>
          }],
          onChange: key => {
            this.setState({
              activeKey: (key as string)
            });
            this.actionRef.current?.reloadAndRest?.();
          }
        },
        settings: []
      }} rowKey='id' pagination={{
        pageSizeOptions: ['20', '100', '500']
      }} dateFormatter='string' search={{
        span: 6,
        defaultCollapsed: false,
        collapseRender:false,
        optionRender: ({
          searchText,
          resetText
        }, {
          form
        }) => [<Button key='search' type='primary' onClick={() => {
          form?.submit();
        }} >
            {searchText}
          </Button>, <Button key='rest' onClick={() => {
          form?.resetFields();
          form?.submit();
        }}>
            {resetText}
          </Button>, <Button key='out' onClick={async () => {
          this.setState({
            spinningFlag: true
          });
          var orderNumber = form?.getFieldValue('order_number');
          var date = form?.getFieldValue('date');
          var params: any = {};

          if (date) {
            params.beginDate = date[0].format('YYYY-MM-DD');
            params.endDate = date[1].format('YYYY-MM-DD'); // params.date=undefined;
          }
          params.order_number = orderNumber;
          params.dealerCode = form?.getFieldValue('dealerCode');
          params.dealerName = form?.getFieldValue('orderNumber');
          params.complete = 0;
          params.manufacturer = form?.getFieldValue('manufacturer');
          var approvalDate = form?.getFieldValue('approvalDate');
          if (approvalDate) {
            params.approvalBeginDate = approvalDate[0].format('YYYY-MM-DD');
            ;
            params.approvalEndDate = approvalDate[1].format('YYYY-MM-DD');
          }

          var val = await exportorderSend(params);

          if (val.errorCode === '200') {
            exportFile(val.data, '发货单.xlsx');
          } else {
            message.error(val.errorMessage);
          }

          this.setState({
            spinningFlag: false
          });
        }}>导出</Button>]
      }} />
    <Drawer width={1200} destroyOnClose={true} title={'详情'} visible={this.state.detailFlag} onClose={() => {
        this.setState({
          detailFlag: false
        });
      }}>
        <Row style={{
          margin: '0px 0 22px 22px'
        }} >
          <Col span={22}></Col>
          <Col span={2}>
            <Button type='primary' onClick={this.printOrder}>打印</Button>
          </Col>
        </Row>  
         <div id='billDetails' >
          <Row style={{
            marginLeft: '22px'
          }}>
            <Col span={5}  ><UpDownLabel title='订单号' texts={[this.state.initData?.order?.order_number]}  /></Col>
            <Col span={5}  ><UpDownLabel title='客户代码' texts={[this.state.dealerCode]}  /></Col>
            <Col span={5}  ><UpDownLabel title='客户名称' texts={[this.state.initData?.order?.dealerName]}  /></Col>
            <Col span={5}  ><UpDownLabel title='订货日期' texts={[this.state.initData?.order?.order_time]}  /></Col>
            <Col span={4}  ><UpDownLabel title='交货日期'	 texts={[this.state.initData?.order?.delivery_time]}  /></Col>
          </Row>
          <Row style={{
            marginLeft: '22px'
          }}  >
            <Col span={5}  ><UpDownLabel title='付款方式' texts={[this.state.initData?.order?.payment_method]}  /></Col>
            <Col span={5}  ><UpDownLabel title='运费方式' texts={[this.state.initData?.order?.postPayMethod]}  /></Col>
            <Col span={5}  ><UpDownLabel title='销售' texts={[this.state.initData?.order?.salesName]}  /></Col>
            <Col span={5}  ><UpDownLabel title='收货人' texts={[this.state.initData?.order?.consignee]}  /></Col>
            <Col span={4}  ><UpDownLabel title='收货电话' texts={[this.state.initData?.order?.mobile]}  /></Col>
          </Row>
          <Row style={{
            marginLeft: '22px'
          }}  >
            <Col span={12}  ><UpDownLabel title='收货地址' texts={[this.state.initData?.order?.provinces_label + this.state.initData?.order?.city_label + this.state.initData?.order?.area_label + ' - ' + this.state.initData?.order?.delivery_address]}  /></Col>
            <Col span={12}  ><UpDownLabel title='出库单地址' texts={[this.state.initData?.order?.realAddress]}  /></Col>
          </Row>
          <Row style={{
            marginLeft: '22px'
          }} d>
            <Col span={12}  ><UpDownLabel title='备注' texts={[this.state.initData?.order?.remarks]}/></Col>
          </Row>
          <ProTable<ProductType> headerTitle='订单产品' toolbar={{
            settings: []
          }} columns={this.pcolumns} dataSource={this.state.initData?.list} rowKey='id' pagination={false} search={false} >
          </ProTable>
        </div>
      </Drawer>
    <DrawerForm title={'发货'} width={1200} visible={this.state.sentFlag} drawerProps={{
        destroyOnClose: true,
        forceRender: true
      }} submitter={{
        searchConfig: {
          submitText: '发货',
          resetText: '取消'
        }
      }} onFinish={async values => {
        var params: any = {
          invoice: {
            orderId: this.state.record.id,
            waybillNo: values.waybillNo
          },
          product: []
        };

        for (var j = 0; j < this.state.proData.length; j++) {
          const item: any = this.state.proData[j]; // var totalNum=0;

          for (var i = 0; i < item.sub.length; i++) {
            var subItem: any = item.sub[i];

            if (subItem.batch.trim() === '') {
              message.error('批号必填');
              return false;
            }

            subItem.batch = subItem.batch.trim();

            if (subItem.numbs === 0) {
              message.error('数量不能为0');
              return false;
            }

            if (!subItem.validityDate) {
              message.error('失效日期必填');
              return false;
            }

            if (subItem.validityDate) {
              subItem.validity = subItem.validityDate.format('YYYY-MM-DD');
            } // totalNum+=subItem.numbs;


            params.product.push(subItem);
          } // if(totalNum>item.numbs){
          //   message.error(item.product_standard+的发货数量不能大于订货数量);
          //   return false;
          // }

        } // console.log(params);


        var val = await delivery(params);

        if (val.errorCode === '200') {
          message.success('发货成功');
          this.actionRef.current?.reloadAndRest?.();
          return true;
        } else {
          message.error(val.errorMessage);
          return false;
        }
      }} onVisibleChange={val => {
        this.setState({
          sentFlag: val
        });

        if (!val) {
          this.setState({
            proData: []
          });
        }
      }} >
        <Row >
          <Col span={12}  >
              <ProFormText name='waybillNo' label='运单号' rules={[{
              required: true,
              message: '请输入运单号'
            }]} />
          </Col>
        </Row>
        <Row>
          <Col span={4}><UpDownLabel title='订单编码' texts={[this.state.record?.order_number]} /></Col>
          <Col span={4}><UpDownLabel title='运费方式' texts={[this.state.record?.postPayMethod]} /></Col>
          <Col span={4}><UpDownLabel title='客户代码' texts={[this.state.record?.dealerCode]} /></Col>
          <Col span={4}><UpDownLabel title='客户' texts={[this.state.record?.dealerName]} /></Col>
          <Col span={4}><UpDownLabel title='订货日期' texts={[this.state.record?.order_time]} /></Col>
          <Col span={4}><UpDownLabel title='交货日期' texts={[this.state.record?.delivery_time]} /></Col>
        </Row>
        <Row >
          <Col span={12}><UpDownLabel title='收货地址' texts={[this.state.record?.consignee + '  ' + this.state.record?.mobile, this.state.record?.provinces_label + this.state.record?.city_label + this.state.record?.area_label + ' - ' + this.state.record?.delivery_address]} /></Col>
          <Col span={12}><UpDownLabel title='出库单地址' texts={[this.state.record?.realAddress]} /></Col>
        </Row>
        <Row >
          <Col span={12}><UpDownLabel title='备注' texts={[this.state.record?.remarks]} /></Col>
        </Row>
        <ProTable className='components-table-demo-nested' dataSource={this.state.proData} columns={this.pCreatecolumns} rowKey='orderProductId' pagination={false} toolbar={[]} search={false} toolBarRender={false} expandable={{
          expandedRowRender,
          defaultExpandAllRows: true,
          expandIconColumnIndex: -1
        }}/>
      </DrawerForm>
      <ModalForm title='发货单导入' onVisibleChange={v => {
        this.setState({
          showImport: v
        });
      }} modalProps={{
        destroyOnClose: true,
        forceRender: true
      }} visible={this.state.showImport} onFinish={async (values: any) => {
        console.log(values);
        return true;
      }}>
             <div style={{
          margin: '10px 0 20px 0'
        }} ><a href='/xwyl/attach/fhd.xlsx' download='发货单模板.xlsx'><Button type='primary'> <FileExcelOutlined/>发货单模板下载</Button></a></div>
            <ProFormUploadDragger label='选择excel导入' name='file' action='/xwyl/delivery/deliveryImport' fieldProps={{
          name: 'file',
          headers: {
            'authorization': (sessionStorage.getItem('token') as string)
          }
        }} max={1} onChange={this.onFileUpload} />

      </ModalForm>
      <Modal visible={this.state.errorVisible} title='导入错误提示' width={800} footer={null} destroyOnClose={true} onCancel={this.handleCancel}>
        <Table dataSource={this.state.errInfo} style={{
          height: 400
        }} columns={this.errorColumn} pagination={false} rowKey='rownum'>
          
        </Table>
      </Modal>
      <Spin spinning={this.state.spinningFlag} style={{
        transform: 'translate(-50%,-50%)',
        left: '50%',
        top: '50%',
        position: 'absolute'
      }}/>
    </PageContainer>;
  }

}

export default Delivery;